//
//  HYQPickerView.m
//  HYQPickerView_Example
//
//  Created by zhuxingjian on 2018/8/28.
//  Copyright © 2018年 zxj1989. All rights reserved.
//

#import "HYQPickerView.h"

static const CGFloat pickerContentHeight = 253;
static const CGFloat pickerTitleHeight = 46;
static const CGFloat pickerItemHeight = 50;

#define PICKER_LINE_COLOR [UIColor colorWithRed:238 / 255.0 green:238 / 255.0 blue:238 / 255.0 alpha:1]

@interface HYQPickerView () <UIPickerViewDelegate, UIPickerViewDataSource, UIGestureRecognizerDelegate>

@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIButton *cancelButton;
@property (nonatomic, strong) UIButton *confirmButton;
@property (nonatomic, strong) UIPickerView *pickerView;
@property (nonatomic, assign) BOOL hasSetSelected;

@end

@implementation HYQPickerView

- (UIView *)contentView
{
    if (!_contentView) {
        _contentView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.bounds) - pickerContentHeight, CGRectGetWidth(self.bounds), pickerContentHeight)];
        _contentView.backgroundColor = [UIColor whiteColor];
        
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:_contentView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight  cornerRadii:CGSizeMake(5, 5)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = _contentView.bounds;
        maskLayer.path = maskPath.CGPath;
        _contentView.layer.mask = maskLayer;
        
        CAShapeLayer *layer = [CAShapeLayer layer];
        layer.backgroundColor = PICKER_LINE_COLOR.CGColor;
        layer.frame = CGRectMake(20, pickerTitleHeight, CGRectGetWidth(self.bounds) - 40, 0.5);
        [_contentView.layer addSublayer:layer];
    }
    return _contentView;
}

- (UIButton *)cancelButton
{
    if (!_cancelButton) {
        _cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _cancelButton.titleLabel.font = [UIFont systemFontOfSize:15];
        [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelButton setTitleColor:[UIColor colorWithRed:153 / 255.0 green:153 / 255.0 blue:153 / 255.0 alpha:1] forState:UIControlStateNormal];
        [_cancelButton addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        _cancelButton.tag = 100;
    }
    return _cancelButton;
}

- (UIButton *)confirmButton
{
    if (!_confirmButton) {
        _confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _confirmButton.titleLabel.font = [UIFont systemFontOfSize:15];
        [_confirmButton setTitle:@"确定" forState:UIControlStateNormal];
        [_confirmButton setTitleColor:[UIColor colorWithRed:247 / 255.0 green:78 / 255.0 blue:70 / 255.0 alpha:1] forState:UIControlStateNormal];
        [_confirmButton addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        _confirmButton.tag = 101;
    }
    return _confirmButton;
}

- (UIPickerView *)pickerView
{
    if (!_pickerView) {
        _pickerView = [[UIPickerView alloc] init];
        _pickerView.backgroundColor = [UIColor whiteColor];
        _pickerView.delegate = self;
        _pickerView.dataSource = self;
        
        CGFloat pickCellH = pickerItemHeight;
        for (int i = 0; i < 2; i++) {
            CAShapeLayer *layer = [CAShapeLayer layer];
            layer.backgroundColor = PICKER_LINE_COLOR.CGColor;
            layer.frame = CGRectMake(20, pickCellH * (i + 1), CGRectGetWidth(self.bounds) - 40, 0.5);
            [_pickerView.layer addSublayer:layer];
        }
        
    }
    return _pickerView;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        [self addSubview:self.contentView];
        
        [self.contentView addSubview:self.cancelButton];
        [self.contentView addSubview:self.confirmButton];
        [self.contentView addSubview:self.pickerView];
        
        self.cancelButton.frame = CGRectMake(0, 0, 70, 45);
        self.confirmButton.frame = CGRectMake(CGRectGetWidth(self.bounds) - 70, 0, 70, 45);
        
        CGFloat top = (pickerContentHeight - pickerItemHeight * 3 - pickerTitleHeight) / 2 + pickerTitleHeight;
        self.pickerView.frame = CGRectMake(0, top, CGRectGetWidth(frame), pickerItemHeight * 3);
        
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hide)];
        tap.delegate = self;
        [self addGestureRecognizer:tap];
    }
    return self;
}

- (void)showAnimation
{
    self.contentView.frame = CGRectMake(0, CGRectGetHeight(self.bounds), CGRectGetWidth(self.bounds), pickerContentHeight);
    [UIView animateWithDuration:0.25 animations:^{
        self.contentView.frame = CGRectMake(0, CGRectGetHeight(self.bounds) - pickerContentHeight, CGRectGetWidth(self.bounds), pickerContentHeight);
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.2];
    }];
}

- (void)hide
{
    [UIView animateWithDuration:0.25 animations:^{
        self.contentView.frame = CGRectMake(0, CGRectGetHeight(self.bounds), CGRectGetWidth(self.bounds), pickerContentHeight);
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
    } completion:^(BOOL finished) {
        if (finished) {
            [self removeFromSuperview];
        }
    }];
}

- (void)btnAction:(UIButton *)btn
{
    if (btn == self.confirmButton) {
        NSMutableArray *selectedIndex = [NSMutableArray arrayWithCapacity:0];
        for (int i = 0; i < self.componentDataArray.count; i++) {
            NSInteger row = [self.pickerView selectedRowInComponent:i];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:i];
            [selectedIndex addObject:indexPath];
        }
        if (self.completedBlock) {
            self.completedBlock([selectedIndex copy]);
        }
    }
    [self hide];
}

#pragma mark --------------- UIPickerViewDataSource -------------
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
{
    return self.componentDataArray.count;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
{
    return [self.componentDataArray[component] count];
}

#pragma mark --------------- UIPickerViewDelegate -------------
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component __TVOS_PROHIBITED;
{
    return CGRectGetWidth(self.bounds) / self.componentDataArray.count;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component __TVOS_PROHIBITED;
{
    return pickerItemHeight;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    
    UILabel *pickerLabel = (UILabel*)view;
    if (!pickerLabel) {
        for (UIView *singleLine in pickerView.subviews) {
            if (singleLine.frame.size.height < 1) {
                singleLine.backgroundColor = [UIColor clearColor];
            }
        }
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor whiteColor]];
        [pickerLabel setFont:[UIFont systemFontOfSize:17]];
    }
    pickerLabel.text = [NSString stringWithFormat:@"%@",[self.componentDataArray[component] objectAtIndex:row]];
    return pickerLabel;
}

- (void)setComponentDataArray:(NSArray *)componentDataArray
{
    _componentDataArray = componentDataArray;
    [self.pickerView reloadAllComponents];
}

- (void)setRowSelected:(NSInteger)row component:(NSInteger)component;
{
    if (!self.componentDataArray.count) {
        NSLog(@"请先设置数据源");
        return;
    }
    if (component >= self.componentDataArray.count) {
        return;
    }
    if (row >= [self.componentDataArray[component] count]) {
        return;
    }
    self.hasSetSelected = YES;
    [self.pickerView selectRow:row inComponent:component animated:YES];
}

- (void)showInView:(UIView *)superView
{
    [superView addSubview:self];
    if (!self.hasSetSelected) {
        for (int i = 0; i < self.componentDataArray.count; i ++) {
            if ([self.pickerView selectedRowInComponent:i] == 0 && [self.componentDataArray[i] count] > 1) {
                [self.pickerView selectRow:1 inComponent:i animated:NO];
            }
        }
    }
    [self showAnimation];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if (touch.view != self) {
        return NO;
    }
    return YES;
}

@end
